import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

import { useRouter } from 'next/navigation'
import Loading from '../components/base/loading'
import Button from '@/app/components/base/button'

import {
  fetchInitValidateStatus,
  fetchSetupStatus,
  getCodeByPhone,
  registerAccountByPhone,
} from '@/service/common'
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
import Toast from '@/app/components/base/toast'

const RegisterForm = () => {
  const { t } = useTranslation()
  const router = useRouter()
  const [loading, setLoading] = useState(true)
  const [isEmailSent, setIsEmailSent] = useState(false)
  const [phone, setPhone] = useState('')
  const [email, setEmail] = useState('')
  const [code, setCode] = useState('')

  const [isCodeSent, setIsCodeSent] = useState(false)
  const handleRegister = async () => {
    try {
      const res = await registerAccountByPhone({
        url: '/register',
        body: { email, phone, code },
      })
      if (res.result === 'success') {
        Toast.notify({
          type: 'success',
          message: '账号注册成功',
          duration: 5000,
        })
        router.push('/signin')
      }
    }
    catch (error) {
      console.error('Request failed:', error)
    }
  }

  const handleSendResetPasswordClick = async () => {
    await handleRegister()
  }
  const toSetPhone = (phone: string) => {
    setPhone(phone)
    phone.length === 11 ? setIsCodeSent(true) : setIsCodeSent(false)
  }

  const handleSendCodeClick = async () => {
    const response = await getCodeByPhone({
      url: `/code/${phone}`,
    })
    if (response.result === 'success') {
      Toast.notify({
        type: 'success',
        message: '短信发送成功',
        duration: 5000,
      })
    }
  }

  useEffect(() => {
    fetchSetupStatus().then((res: SetupStatusResponse) => {
      fetchInitValidateStatus().then((res: InitValidateStatusResponse) => {
        if (res.status === 'not_started')
          window.location.href = '/init'
      })

      setLoading(false)
    })
  }, [])

  return (
    loading
      ? <Loading/>
      : <>
        <div className="sm:mx-auto sm:w-full sm:max-w-md">
          <h2 className="text-[32px] font-bold text-gray-900">
            注册账号
          </h2>
          <p className='mt-1 text-sm text-gray-600'>
            请输入您的手机账号以重置密码。我们将向您发送短信进行验证，请收到验证码后进行输入, 密码默认为 dify123456
          </p>
        </div>
        <div className="grow mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="bg-white ">
            <form>
              {!isEmailSent && (
                <div className='mb-5'>
                  <label className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
                    手机号
                  </label>
                  <div className="mt-1">
                    <input
                      placeholder='输入手机号码'
                      value={phone}
                      onChange={(e) => { toSetPhone(e.target.value) }}
                      className={'appearance-none block w-full rounded-lg pl-[14px] px-3 py-2 border border-gray-200 hover:border-gray-300 hover:shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 placeholder-gray-400 caret-primary-600 sm:text-sm'}
                    />
                    {
                      isCodeSent && <Button variant='primary' className='w-full' onClick={handleSendCodeClick}>
                        获取验证码
                      </Button>
                    }
                  </div>
                  <label htmlFor="email" className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
                    验证码
                  </label>
                  <div className="mt-1">
                    <input
                      placeholder='输入验证码'
                      value={code}
                      onChange={(e) => { setCode(e.target.value) }}
                      className={'appearance-none block w-full rounded-lg pl-[14px] px-3 py-2 border border-gray-200 hover:border-gray-300 hover:shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 placeholder-gray-400 caret-primary-600 sm:text-sm'}
                    />
                  </div>
                  <label htmlFor="email" className="my-2 flex items-center justify-between text-sm font-medium text-gray-900">
                    邮箱
                  </label>
                  <div className="mt-1">
                    <input
                      value={email}
                      onChange={e => setEmail(e.target.value)}
                      placeholder='输入邮箱地址'
                      className={'appearance-none block w-full rounded-lg pl-[14px] px-3 py-2 border border-gray-200 hover:border-gray-300 hover:shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 placeholder-gray-400 caret-primary-600 sm:text-sm'}
                    />
                  </div>
                </div>
              )}
              <div>
                <Button variant='primary' className='w-full' onClick={handleSendResetPasswordClick}>
                  注册账号
                </Button>
              </div>
            </form>
          </div>
        </div>
      </>
  )
}

export default RegisterForm
